package com.sfac.javaEE.filter;

import com.sfac.javaEE.entity.User;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginFilter", urlPatterns = {"/*"})
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();
        if (uri.contains("login") || uri.contains("register")) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            User user = (User) request.getSession().getAttribute("user"); //这里是登录返回过来的User实体类对象
            if (user == null) {
                request.setAttribute("msg", "请登录！");
                request.getRequestDispatcher("/WEB-INF/template/account/login.jsp").forward(request, response);
            } else {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }

    }
}
